package com.springboot.pratice.common.config;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @Description: <描述>
 * @Author: Pei-Hsun Zhong zhongpx@chinatelecom.cn
 * @Date: 2021-06-23 17:30
 * Copyright © 2020 ctwing
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    RestTemplate restTemplate(@Autowired ClientHttpRequestFactory simpleClientHttpRequestFactory) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {


        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();

        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext,
                new String[]{"TLSv1"},
                null,
                NoopHostnameVerifier.INSTANCE);

        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(csf)
                .build();

        HttpComponentsClientHttpRequestFactory requestFactory =
                new HttpComponentsClientHttpRequestFactory();

        requestFactory.setHttpClient(httpClient);
        //连接超时：5秒
        requestFactory.setConnectTimeout(5000);
        //读取超时：10秒
        requestFactory.setReadTimeout(10000);
        return new RestTemplate(requestFactory);

//        return new RestTemplate(simpleClientHttpRequestFactory);
    }


    @Bean
    ClientHttpRequestFactory simpleClientHttpRequestFactory() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        //连接超时：5秒
        factory.setConnectTimeout(5000);
        //读取超时：10秒
        factory.setReadTimeout(10000);
        return factory;
    }
}
